<template>
  <a-modal
    :open="visible"
    title="扫描发现设备"
    :confirm-loading="isScanning"
    :ok-text="isScanning ? '正在扫描...' : '开始扫描'"
    cancel-text="取消"
    @ok="handleDiscover"
    @cancel="handleCancel"
    :mask-closable="!isScanning"
    :closable="!isScanning"
  >
    <a-form layout="vertical" :model="scanParams">
      <a-form-item label="IP 地址范围" required>
        <a-input v-model:value="scanParams.ipRange" placeholder="例如: 192.168.1.1-254" :disabled="isScanning" />
      </a-form-item>
      <a-form-item label="设备端口" required>
        <a-input-number v-model:value="scanParams.port" style="width: 100%;" :disabled="isScanning" />
      </a-form-item>
      <a-form-item label="设备通用用户名" required>
        <a-input v-model:value="scanParams.username" placeholder="例如: admin" :disabled="isScanning" />
      </a-form-item>
      <a-form-item label="设备通用密码" required>
        <a-input-password v-model:value="scanParams.password" :disabled="isScanning" />
      </a-form-item>
    </a-form>
    
    <!-- 扫描进度显示 -->
    <div v-if="isScanning || scanCompleted" class="scan-progress-wrapper">
      <a-progress :percent="scanProgress" :status="progressStatus" />
      <p class="scan-status-text">{{ scanStatusText }}</p>
    </div>
  </a-modal>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { message } from 'ant-design-vue';
import { startScan, getScanStatus } from '@/api/deviceScans';

const props = defineProps({
  visible: { type: Boolean, required: true }
});

const emit = defineEmits(['update:visible', 'scan-completed']);

const isScanning = ref(false);
const scanCompleted = ref(false);
const scanProgress = ref(0);
const scanStatusText = ref('');
const scanParams = reactive({
  ipRange: '192.168.1.1-254',
  port: 80,
  username: 'admin',
  password: 'your_device_password', // 提示用户输入
});

let scanTaskId = null;
let pollInterval = null;

const progressStatus = computed(() => {
    if (scanStatusText.value.includes('失败')) return 'exception';
    if (scanCompleted.value) return 'success';
    return 'active';
});


const pollScanStatus = async () => {
  try {
    const response = await getScanStatus(scanTaskId);
    const status = response.data;
    
    scanProgress.value = status.total > 0 ? Math.round((status.progress / status.total) * 100) : 0;
    scanStatusText.value = `扫描中... (${status.progress}/${status.total})，已发现 ${status.foundCount} 台设备。`;

    if (status.status === 'COMPLETED' || status.status === 'FAILED') {
      clearInterval(pollInterval);
      isScanning.value = false;
      scanCompleted.value = true;
      
      if(status.status === 'COMPLETED') {
        scanStatusText.value = `扫描完成！共发现 ${status.foundCount} 台设备。`;
        message.success(scanStatusText.value);
        emit('scan-completed');
      } else {
        scanStatusText.value = `扫描失败: ${status.error}`;
        message.error(scanStatusText.value);
      }
    }
  } catch (error) {
    clearInterval(pollInterval);
    isScanning.value = false;
    scanCompleted.value = true;
    scanStatusText.value = '查询扫描状态失败，任务可能已在后台中断。';
    message.error(scanStatusText.value);
  }
};

const handleDiscover = async () => {
  // TODO: 表单校验
  isScanning.value = true;
  scanCompleted.value = false;
  scanProgress.value = 0;
  scanStatusText.value = '正在启动扫描任务...';
  
  try {
    const response = await startScan(scanParams);
    scanTaskId = response.data.taskId;
    pollInterval = setInterval(pollScanStatus, 2000); // 每2秒轮询一次
  } catch (error) {
    message.error('启动扫描任务失败！');
    isScanning.value = false;
  }
};

const handleCancel = () => {
  if (isScanning.value) {
    message.warn('扫描正在进行中，无法关闭。');
    return;
  }
  emit('update:visible', false);
  // 重置状态
  scanCompleted.value = false;
  scanProgress.value = 0;
  scanStatusText.value = '';
};

</script>

<style scoped>
.scan-progress-wrapper {
  margin-top: 24px;
}
.scan-status-text {
  margin-top: 8px;
  text-align: center;
  color: #595959;
}
</style>